<template>
  <div class="personnel-list">
    <div class="page-title">人员列表</div>

    <!-- 数据完整度统计概览 -->
    <div class="statistics-overview" v-if="total > 0">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
              <el-icon :size="24"><DataAnalysis /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">总记录数</div>
              <div class="stat-value">{{ total }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" :style="{ background: getOverallCompletenessGradient() }">
              <el-icon :size="24"><PieChart /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">平均数据完整度</div>
              <div class="stat-value" :style="{ color: getOverallCompletenessColor() }">
                {{ getOverallCompleteness().toFixed(1) }}%
              </div>
              <div class="stat-desc">{{ getOverallCompletenessDesc() }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
              <el-icon :size="24"><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">平均空置率</div>
              <div class="stat-value" style="color: #f56c6c">
                {{ (100 - getOverallCompleteness()).toFixed(1) }}%
              </div>
              <div class="stat-desc">{{ getAverageNullFields() }} 个字段缺失</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
              <el-icon :size="24"><DataLine /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">完整度分布</div>
              <div class="stat-distribution">
                <span class="dist-item">
                  <el-tag type="success" size="small" effect="plain">优秀 {{ getCompletenessDistribution().excellent }}</el-tag>
                </span>
                <span class="dist-item">
                  <el-tag type="primary" size="small" effect="plain">良好 {{ getCompletenessDistribution().good }}</el-tag>
                </span>
                <span class="dist-item">
                  <el-tag type="warning" size="small" effect="plain">一般 {{ getCompletenessDistribution().fair }}</el-tag>
                </span>
                <span class="dist-item">
                  <el-tag type="danger" size="small" effect="plain">差 {{ getCompletenessDistribution().poor }}</el-tag>
                </span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="page-card">
      <!-- 筛选条件 -->
      <el-form :inline="true" :model="queryForm">
        <el-form-item label="姓名搜索">
          <el-input 
            v-model="queryForm.keyword" 
            placeholder="输入中文名或英文名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
            <el-option label="全部" value="all" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button 
            type="warning" 
            @click="handleFixEducation" 
            :loading="fixingEducation"
            :icon="MagicStick"
          >
            修复教育信息
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar 
              :src="getAvatarUrl(row.avatar_path)" 
              :size="30"
              fit="cover"
            >
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="chinese_name" label="中文名" width="120" show-overflow-tooltip />
        <el-table-column prop="english_name" label="英文名" width="150" show-overflow-tooltip />
        <el-table-column prop="military_rank" label="军衔" width="120" />
        <el-table-column prop="organization" label="单位" min-width="200" show-overflow-tooltip />
        <el-table-column prop="current_position" label="职务" min-width="180" show-overflow-tooltip />
        <el-table-column label="数据完整度" width="120" align="center" sortable :sort-method="(a, b) => calculateNullRate(a) - calculateNullRate(b)">
          <template #default="{ row }">
            <el-tag 
              :type="getNullRateType(calculateNullRate(row))"
              effect="dark"
            >
              {{ (100 - calculateNullRate(row)).toFixed(1) }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="audit_status" label="审核状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.audit_status === 'approved'" type="success">已通过</el-tag>
            <el-tag v-else-if="row.audit_status === 'rejected'" type="danger">已驳回</el-tag>
            <el-tag v-else type="info">待审核</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditor_name" label="审核人" width="100" />
        <el-table-column prop="audit_time" label="审核时间" width="180">
          <template #default="{ row }">
            {{ row.audit_time ? dayjs(row.audit_time).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleView(row.id)">
              详情
            </el-button>
            <el-button type="warning" size="small" link @click="handleEdit(row.id)">
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              link 
              @click="handleReprocess(row.id)"
              :loading="reprocessingIds.includes(row.id)"
            >
              重新解析
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadData"
        @current-change="loadData"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="人员详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="detailData" class="detail-content">
        <!-- 头像和基本信息卡片 -->
        <el-card class="header-card" shadow="never">
          <div class="header-info">
            <el-avatar 
              :src="getAvatarUrl(detailData.processedRecord?.avatar_path)" 
              :size="100"
              fit="cover"
            >
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
            <div class="basic-info">
              <h2>{{ detailData.processedRecord?.chinese_name || '-' }}</h2>
              <p class="english-name">{{ detailData.processedRecord?.english_name || '-' }}</p>
              <div class="tags">
                <el-tag v-if="detailData.processedRecord?.military_rank" type="info">
                  {{ detailData.processedRecord.military_rank }}
                </el-tag>
                <el-tag v-if="detailData.processedRecord?.country_region" type="warning">
                  {{ detailData.processedRecord.country_region }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 详细信息标签页 -->
        <el-tabs class="detail-tabs">
          <el-tab-pane label="基本信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="中文名">{{ detailData.processedRecord?.chinese_name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="英文名">{{ detailData.processedRecord?.english_name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="国家/地区">{{ detailData.processedRecord?.country_region || '-' }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ detailData.processedRecord?.gender || '-' }}</el-descriptions-item>
              <el-descriptions-item label="出生日期">{{ detailData.processedRecord?.birth_date || '-' }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ detailData.processedRecord?.age || '-' }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ detailData.processedRecord?.email || '-' }}</el-descriptions-item>
              <el-descriptions-item label="电话">{{ detailData.processedRecord?.phone || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="教育信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="毕业院校">{{ detailData.processedRecord?.graduate_school || '-' }}</el-descriptions-item>
              <el-descriptions-item label="最高学历">{{ detailData.processedRecord?.education_level || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="军职信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="军兵种">{{ detailData.processedRecord?.military_branch || '-' }}</el-descriptions-item>
              <el-descriptions-item label="军衔">{{ detailData.processedRecord?.military_rank || '-' }}</el-descriptions-item>
              <el-descriptions-item label="所在机构" :span="2">{{ detailData.processedRecord?.organization || '-' }}</el-descriptions-item>
              <el-descriptions-item label="当前职务">{{ detailData.processedRecord?.current_position || '-' }}</el-descriptions-item>
              <el-descriptions-item label="任职日期">{{ detailData.processedRecord?.position_start_date || '-' }}</el-descriptions-item>
              <el-descriptions-item label="工作状态">{{ detailData.processedRecord?.work_status || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="简介">
            <h4>中文简介</h4>
            <div class="biography-content">{{ detailData.processedRecord?.chinese_biography || '暂无' }}</div>
            <h4 style="margin-top: 20px">英文简介</h4>
            <div class="biography-content">{{ detailData.processedRecord?.english_biography || '暂无' }}</div>
          </el-tab-pane>

          <el-tab-pane label="经历">
            <h4>工作经历</h4>
            <div class="experience-content">{{ detailData.processedRecord?.work_experience_cn || '暂无' }}</div>
            <h4 style="margin-top: 20px">教育经历</h4>
            <div class="experience-content">{{ detailData.processedRecord?.education_experience_cn || '暂无' }}</div>
          </el-tab-pane>

          <el-tab-pane label="审核信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="审核状态">
                <el-tag v-if="detailData.rawRecord?.audit_status === 'approved'" type="success">已通过</el-tag>
                <el-tag v-else-if="detailData.rawRecord?.audit_status === 'rejected'" type="danger">已驳回</el-tag>
                <el-tag v-else type="info">待审核</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="审核时间">{{ detailData.rawRecord?.audit_time ? dayjs(detailData.rawRecord.audit_time).format('YYYY-MM-DD HH:mm:ss') : '-' }}</el-descriptions-item>
              <el-descriptions-item label="审核人">{{ detailData.rawRecord?.auditor_name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="审核人工号">{{ detailData.rawRecord?.auditor_id || '-' }}</el-descriptions-item>
              <el-descriptions-item label="审核意见" :span="2">{{ detailData.rawRecord?.audit_comment || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="数据完整度">
            <div class="completeness-overview">
              <div class="overview-card">
                <div class="overview-label">数据完整度</div>
                <div class="overview-value" :style="{ color: getCompletenessColor(detailData.processedRecord) }">
                  {{ (100 - calculateNullRate(detailData.processedRecord)).toFixed(1) }}%
                </div>
                <div class="overview-desc">
                  {{ getCompletenessLevel(detailData.processedRecord) }}
                </div>
              </div>
              <div class="overview-card">
                <div class="overview-label">已填充字段</div>
                <div class="overview-value" style="color: #67c23a">
                  {{ getFilledFieldsCount(detailData.processedRecord) }}
                </div>
                <div class="overview-desc">共22个字段</div>
              </div>
              <div class="overview-card">
                <div class="overview-label">空缺字段</div>
                <div class="overview-value" style="color: #f56c6c">
                  {{ getNullFieldsCount(detailData.processedRecord) }}
                </div>
                <div class="overview-desc">需要补充</div>
              </div>
            </div>

            <el-divider />

            <h4>字段详情</h4>
            <div class="field-list">
              <div 
                v-for="field in getFieldsStatus(detailData.processedRecord)" 
                :key="field.key"
                class="field-item"
                :class="{ 'field-empty': field.isEmpty }"
              >
                <div class="field-name">
                  <el-icon v-if="!field.isEmpty" style="color: #67c23a"><CircleCheckFilled /></el-icon>
                  <el-icon v-else style="color: #f56c6c"><CircleCloseFilled /></el-icon>
                  <span>{{ field.label }}</span>
                </div>
                <div class="field-status">
                  <el-tag v-if="!field.isEmpty" type="success" size="small">已填充</el-tag>
                  <el-tag v-else type="danger" size="small">空缺</el-tag>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <el-button type="primary" @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editVisible"
      title="编辑人员信息"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-form 
        v-if="editForm" 
        :model="editForm" 
        label-width="120px"
        ref="editFormRef"
      >
        <el-tabs>
          <el-tab-pane label="基本信息">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="中文名" prop="chinese_name">
                  <el-input v-model="editForm.chinese_name" placeholder="请输入中文名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="英文名" prop="english_name">
                  <el-input v-model="editForm.english_name" placeholder="请输入英文名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="国家/地区" prop="country_region">
                  <el-input v-model="editForm.country_region" placeholder="请输入国家/地区" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birth_date">
                  <el-input v-model="editForm.birth_date" placeholder="格式：YYYY 或 YYYY-MM 或 YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input-number v-model="editForm.age" :min="0" :max="120" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="editForm.phone" placeholder="请输入电话" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="教育信息">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="毕业院校" prop="graduate_school">
                  <el-input v-model="editForm.graduate_school" placeholder="请输入毕业院校" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最高学历" prop="education_level">
                  <el-input v-model="editForm.education_level" placeholder="请输入最高学历" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="军职信息">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="军兵种" prop="military_branch">
                  <el-input v-model="editForm.military_branch" placeholder="请输入军兵种" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="军衔" prop="military_rank">
                  <el-input v-model="editForm.military_rank" placeholder="请输入军衔" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="所在机构" prop="organization">
                  <el-input v-model="editForm.organization" placeholder="请输入所在机构" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="当前职务" prop="current_position">
                  <el-input v-model="editForm.current_position" placeholder="请输入当前职务" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任职日期" prop="position_start_date">
                  <el-input v-model="editForm.position_start_date" placeholder="格式：YYYY 或 YYYY-MM 或 YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工作状态" prop="work_status">
                  <el-input v-model="editForm.work_status" placeholder="请输入工作状态" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="经历">
            <el-form-item label="工作经历" prop="work_experience_cn">
              <el-input 
                v-model="editForm.work_experience_cn" 
                type="textarea" 
                :rows="6"
                placeholder="请输入工作经历"
              />
            </el-form-item>
            <el-form-item label="教育经历" prop="education_experience_cn">
              <el-input 
                v-model="editForm.education_experience_cn" 
                type="textarea" 
                :rows="6"
                placeholder="请输入教育经历"
              />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="简介">
            <el-form-item label="中文简介" prop="chinese_biography">
              <el-input 
                v-model="editForm.chinese_biography" 
                type="textarea" 
                :rows="10"
                placeholder="请输入中文简介"
              />
            </el-form-item>
            <el-form-item label="英文简介" prop="english_biography">
              <el-input 
                v-model="editForm.english_biography" 
                type="textarea" 
                :rows="10"
                placeholder="请输入英文简介"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate" :loading="updating">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CircleCheckFilled, CircleCloseFilled, DataAnalysis, PieChart, Warning, DataLine, MagicStick } from '@element-plus/icons-vue'
import { personnelApi } from '@/api/personnel'
import dayjs from 'dayjs'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const tableData = ref([])
const allData = ref([]) // 存储所有数据用于前端搜索

const queryForm = reactive({
  status: 'approved', // 默认显示已通过
  keyword: '' // 搜索关键字
})

const detailVisible = ref(false)
const detailData = ref(null)

// 编辑相关
const editVisible = ref(false)
const editForm = ref(null)
const editFormRef = ref(null)
const updating = ref(false)
const editRecordId = ref(null)

// 修复教育信息
const fixingEducation = ref(false)

// 重新解析相关
const reprocessingIds = ref([])

// 获取头像URL（处理相对路径）
const getAvatarUrl = (path) => {
  if (!path) return ''
  
  // 如果已经是完整URL，直接返回
  if (path.startsWith('http://') || path.startsWith('https://')) {
    return path
  }
  
  // 将反斜杠转换为正斜杠
  let normalizedPath = path.replace(/\\/g, '/')
  
  // 如果路径以 uploads/avatars/ 开头，添加前导斜杠
  if (normalizedPath.startsWith('uploads/avatars/')) {
    return '/' + normalizedPath
  }
  
  // 如果路径以 ./uploads 开头，去掉点号
  if (normalizedPath.startsWith('./uploads')) {
    return normalizedPath.substring(1)
  }
  
  // 其他情况，确保有前导斜杠
  return normalizedPath.startsWith('/') ? normalizedPath : '/' + normalizedPath
}

// 计算空值率（返回百分比数值）
const calculateNullRate = (row) => {
  // 定义需要统计的22个字段
  const fields = [
    'country_region',      // 国家/地区
    'chinese_name',        // 中文名
    'english_name',        // 英文名
    'gender',              // 性别
    'birth_date',          // 出生日期
    'age',                 // 年龄
    'email',               // 邮箱
    'phone',               // 电话
    'graduate_school',     // 毕业院校
    'education_level',     // 学历
    'military_branch',     // 所属军兵种
    'military_rank',       // 军衔
    'organization',        // 所在机构
    'current_position',    // 当前职务
    'position_start_date', // 任职日期
    'avatar_path',         // 头像
    'english_biography',   // 英文简介
    'chinese_biography',   // 中文简介
    'work_experience_cn',  // 工作经历
    'education_experience_cn', // 教育经历
    'work_status',         // 工作状态
    'data_source'          // 数据来源
  ]
  
  // 统计空值数量
  let nullCount = 0
  fields.forEach(field => {
    const value = row[field]
    // 判断为空：null、undefined、空字符串、或只包含空白字符
    if (value === null || 
        value === undefined || 
        value === '' || 
        (typeof value === 'string' && value.trim() === '')) {
      nullCount++
    }
  })
  
  // 返回空值率（百分比）
  return (nullCount / fields.length) * 100
}

// 根据空值率返回标签类型（颜色）
const getNullRateType = (nullRate) => {
  // 转换为完整度（100% - 空值率）
  const completeness = 100 - nullRate
  
  if (completeness >= 80) return 'success'  // 绿色：80-100%（优秀）
  if (completeness >= 60) return 'primary'  // 蓝色：60-79%（良好）
  if (completeness >= 40) return 'warning'  // 橙色：40-59%（一般）
  return 'danger'                           // 红色：0-39%（差）
}

// 获取完整度颜色
const getCompletenessColor = (record) => {
  const completeness = 100 - calculateNullRate(record)
  if (completeness >= 80) return '#67c23a'  // 绿色
  if (completeness >= 60) return '#409eff'  // 蓝色
  if (completeness >= 40) return '#e6a23c'  // 橙色
  return '#f56c6c'                          // 红色
}

// 获取完整度等级描述
const getCompletenessLevel = (record) => {
  const completeness = 100 - calculateNullRate(record)
  if (completeness >= 80) return '优秀 - 数据完整度高'
  if (completeness >= 60) return '良好 - 数据较完整'
  if (completeness >= 40) return '一般 - 数据需要补充'
  return '差 - 数据缺失严重'
}

// 获取已填充字段数量
const getFilledFieldsCount = (record) => {
  const fields = [
    'country_region', 'chinese_name', 'english_name', 'gender', 'birth_date',
    'age', 'email', 'phone', 'graduate_school', 'education_level',
    'military_branch', 'military_rank', 'organization', 'current_position',
    'position_start_date', 'avatar_path', 'english_biography', 'chinese_biography',
    'work_experience_cn', 'education_experience_cn', 'work_status', 'data_source'
  ]
  
  let filledCount = 0
  fields.forEach(field => {
    const value = record[field]
    if (value !== null && value !== undefined && value !== '' && 
        (typeof value !== 'string' || value.trim() !== '')) {
      filledCount++
    }
  })
  
  return filledCount
}

// 获取空缺字段数量
const getNullFieldsCount = (record) => {
  return 22 - getFilledFieldsCount(record)
}

// 获取所有字段的状态
const getFieldsStatus = (record) => {
  const fieldDefinitions = [
    { key: 'country_region', label: '国家/地区' },
    { key: 'chinese_name', label: '中文名' },
    { key: 'english_name', label: '英文名' },
    { key: 'gender', label: '性别' },
    { key: 'birth_date', label: '出生日期' },
    { key: 'age', label: '年龄' },
    { key: 'email', label: '邮箱' },
    { key: 'phone', label: '电话' },
    { key: 'graduate_school', label: '毕业院校' },
    { key: 'education_level', label: '学历' },
    { key: 'military_branch', label: '所属军兵种' },
    { key: 'military_rank', label: '军衔' },
    { key: 'organization', label: '所在机构' },
    { key: 'current_position', label: '当前职务' },
    { key: 'position_start_date', label: '任职日期' },
    { key: 'avatar_path', label: '头像' },
    { key: 'english_biography', label: '英文简介' },
    { key: 'chinese_biography', label: '中文简介' },
    { key: 'work_experience_cn', label: '工作经历' },
    { key: 'education_experience_cn', label: '教育经历' },
    { key: 'work_status', label: '工作状态' },
    { key: 'data_source', label: '数据来源' }
  ]
  
  return fieldDefinitions.map(field => {
    const value = record[field.key]
    const isEmpty = value === null || value === undefined || value === '' || 
                    (typeof value === 'string' && value.trim() === '')
    return {
      key: field.key,
      label: field.label,
      isEmpty: isEmpty
    }
  })
}

// ========== 总体统计函数 ==========

// 计算总体平均数据完整度
const getOverallCompleteness = () => {
  if (tableData.value.length === 0) return 0
  
  const totalCompleteness = tableData.value.reduce((sum, row) => {
    return sum + (100 - calculateNullRate(row))
  }, 0)
  
  return totalCompleteness / tableData.value.length
}

// 获取总体完整度颜色
const getOverallCompletenessColor = () => {
  const completeness = getOverallCompleteness()
  if (completeness >= 80) return '#67c23a'  // 绿色
  if (completeness >= 60) return '#409eff'  // 蓝色
  if (completeness >= 40) return '#e6a23c'  // 橙色
  return '#f56c6c'                          // 红色
}

// 获取总体完整度渐变背景
const getOverallCompletenessGradient = () => {
  const completeness = getOverallCompleteness()
  if (completeness >= 80) return 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)'
  if (completeness >= 60) return 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)'
  if (completeness >= 40) return 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)'
  return 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)'
}

// 获取总体完整度描述
const getOverallCompletenessDesc = () => {
  const completeness = getOverallCompleteness()
  if (completeness >= 80) return '整体数据质量优秀'
  if (completeness >= 60) return '整体数据质量良好'
  if (completeness >= 40) return '数据需要补充完善'
  return '数据缺失较为严重'
}

// 计算平均空缺字段数
const getAverageNullFields = () => {
  if (tableData.value.length === 0) return 0
  
  const totalNullFields = tableData.value.reduce((sum, row) => {
    return sum + getNullFieldsCount(row)
  }, 0)
  
  return (totalNullFields / tableData.value.length).toFixed(1)
}

// 获取完整度分布统计
const getCompletenessDistribution = () => {
  const distribution = {
    excellent: 0,  // 80-100%
    good: 0,       // 60-79%
    fair: 0,       // 40-59%
    poor: 0        // 0-39%
  }
  
  tableData.value.forEach(row => {
    const completeness = 100 - calculateNullRate(row)
    if (completeness >= 80) distribution.excellent++
    else if (completeness >= 60) distribution.good++
    else if (completeness >= 40) distribution.fair++
    else distribution.poor++
  })
  
  return distribution
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const result = await personnelApi.getAuditedRecords(
      queryForm.status,
      currentPage.value,
      pageSize.value
    )
    if (result.success) {
      allData.value = result.data
      total.value = result.pagination.total
      // 应用关键字过滤
      filterData()
    }
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 前端过滤数据（根据关键字搜索）
const filterData = () => {
  if (!queryForm.keyword) {
    tableData.value = allData.value
    return
  }
  
  const keyword = queryForm.keyword.toLowerCase()
  tableData.value = allData.value.filter(item => {
    return (
      (item.chinese_name && item.chinese_name.toLowerCase().includes(keyword)) ||
      (item.english_name && item.english_name.toLowerCase().includes(keyword))
    )
  })
}

// 查询
const handleQuery = () => {
  if (queryForm.keyword) {
    // 如果有关键字，只做前端过滤
    filterData()
  } else {
    // 没有关键字，重新加载数据
    currentPage.value = 1
    loadData()
  }
}

// 重置
const handleReset = () => {
  queryForm.status = 'approved' // 重置为默认的已通过
  queryForm.keyword = ''
  currentPage.value = 1
  loadData()
}

// 查看详情
const handleView = async (id) => {
  try {
    const result = await personnelApi.getDetail(id)
    if (result.success) {
      detailData.value = result
      detailVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取详情失败: ' + error.message)
  }
}

// 编辑
const handleEdit = async (id) => {
  try {
    const result = await personnelApi.getDetail(id)
    if (result.success && result.processedRecord) {
      editRecordId.value = id
      // 复制数据到编辑表单
      editForm.value = {
        country_region: result.processedRecord.country_region || '',
        chinese_name: result.processedRecord.chinese_name || '',
        english_name: result.processedRecord.english_name || '',
        gender: result.processedRecord.gender || '',
        birth_date: result.processedRecord.birth_date || '',
        age: result.processedRecord.age || null,
        email: result.processedRecord.email || '',
        phone: result.processedRecord.phone || '',
        graduate_school: result.processedRecord.graduate_school || '',
        education_level: result.processedRecord.education_level || '',
        military_branch: result.processedRecord.military_branch || '',
        military_rank: result.processedRecord.military_rank || '',
        organization: result.processedRecord.organization || '',
        current_position: result.processedRecord.current_position || '',
        position_start_date: result.processedRecord.position_start_date || '',
        work_status: result.processedRecord.work_status || '',
        work_experience_cn: result.processedRecord.work_experience_cn || '',
        education_experience_cn: result.processedRecord.education_experience_cn || '',
        chinese_biography: result.processedRecord.chinese_biography || '',
        english_biography: result.processedRecord.english_biography || ''
      }
      editVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取详情失败: ' + error.message)
  }
}

// 更新
const handleUpdate = async () => {
  if (!editRecordId.value || !editForm.value) {
    return
  }

  updating.value = true
  try {
    await personnelApi.updatePersonnel(editRecordId.value, editForm.value)
    ElMessage.success('更新成功')
    editVisible.value = false
    editForm.value = null
    editRecordId.value = null
    // 刷新列表
    await loadData()
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message))
  } finally {
    updating.value = false
  }
}

// 修复教育信息
const handleFixEducation = async () => {
  try {
    const result = await ElMessageBox.confirm(
      '将使用AI逐条检查所有已审核记录的教育信息，自动修正最高学历与毕业院校的对应关系。此操作可能需要较长时间，是否继续？',
      '批量修复教育信息',
      {
        confirmButtonText: '开始修复',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (result === 'confirm') {
      fixingEducation.value = true
      ElMessage.info('开始修复教育信息，请等待...')

      const response = await personnelApi.fixEducationInfo()
      
      if (response.success) {
        const { results } = response
        ElMessage.success({
          message: `修复完成！总计:${results.total}条，成功:${results.success}条，更新:${results.updated}条，失败:${results.failed}条`,
          duration: 5000
        })
        
        // 刷新列表
        await loadData()
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('修复失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    fixingEducation.value = false
  }
}

// 重新解析单条记录
const handleReprocess = async (id) => {
  try {
    const result = await ElMessageBox.confirm(
      '将根据该记录的原始数据重新进行完整的数据处理和解析，包括AI提取、翻译等步骤。这将覆盖当前的所有处理后数据，是否继续？',
      '重新解析数据',
      {
        confirmButtonText: '确认重新解析',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (result === 'confirm') {
      // 添加到处理中列表
      reprocessingIds.value.push(id)
      
      ElMessage.info('开始重新解析，请稍候...')

      const response = await personnelApi.reprocessRecord(id)
      
      if (response.success) {
        ElMessage.success('重新解析成功！数据已更新')
        
        // 刷新列表
        await loadData()
      } else {
        throw new Error(response.message || '重新解析失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重新解析失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    // 从处理中列表移除
    const index = reprocessingIds.value.indexOf(id)
    if (index > -1) {
      reprocessingIds.value.splice(index, 1)
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.personnel-list {
  h4 {
    margin-bottom: 12px;
    color: #303133;
    font-weight: 600;
  }

  p {
    color: #606266;
  }

  // 统计概览样式
  .statistics-overview {
    margin-bottom: 16px;
    animation: fadeInUp 0.5s ease-out;

    .stat-card {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      background: white;
      border-radius: 6px;
      box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      height: 100%;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 3px 12px 0 rgba(0, 0, 0, 0.12);
      }

      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        margin-right: 12px;
        flex-shrink: 0;

        .el-icon {
          font-size: 24px;
        }
      }

      .stat-content {
        flex: 1;
        min-width: 0;

        .stat-label {
          font-size: 12px;
          color: #909399;
          margin-bottom: 4px;
        }

        .stat-value {
          font-size: 22px;
          font-weight: bold;
          color: #303133;
          line-height: 1.2;
          margin-bottom: 2px;
        }

        .stat-desc {
          font-size: 11px;
          color: #909399;
        }

        .stat-distribution {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
          margin-top: 4px;

          .dist-item {
            .el-tag {
              font-size: 11px;
              padding: 0 6px;
              height: 20px;
              line-height: 20px;
            }
          }
        }
      }
    }
  }

  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  // 详情对话框样式
  .detail-content {
    .header-card {
      margin-bottom: 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      
      :deep(.el-card__body) {
        padding: 24px;
      }

      .header-info {
        display: flex;
        align-items: center;
        gap: 24px;

        .el-avatar {
          border: 4px solid rgba(255, 255, 255, 0.9);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .basic-info {
          flex: 1;
          color: white;

          h2 {
            margin: 0 0 8px 0;
            font-size: 28px;
            font-weight: 600;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }

          .english-name {
            margin: 0 0 12px 0;
            font-size: 16px;
            opacity: 0.9;
          }

          .tags {
            display: flex;
            gap: 8px;
            
            .el-tag {
              font-size: 13px;
            }
          }
        }
      }
    }

    .detail-tabs {
      margin-top: 20px;
    }

    .biography-content,
    .experience-content {
      padding: 16px;
      background-color: #f5f7fa;
      border-radius: 4px;
      line-height: 1.8;
      color: #606266;
      white-space: pre-wrap;
      word-wrap: break-word;
    }

    .biography-content {
      min-height: 100px;
    }

    .experience-content {
      min-height: 80px;
    }

    // 数据完整度样式
    .completeness-overview {
      display: flex;
      gap: 24px;
      margin-bottom: 24px;

      .overview-card {
        flex: 1;
        padding: 24px;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        border-radius: 8px;
        text-align: center;

        .overview-label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 12px;
        }

        .overview-value {
          font-size: 36px;
          font-weight: bold;
          margin-bottom: 8px;
        }

        .overview-desc {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .field-list {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;

      .field-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        background-color: #f5f7fa;
        border-radius: 4px;
        border-left: 3px solid #67c23a;
        transition: all 0.3s;

        &:hover {
          background-color: #ecf5ff;
          transform: translateX(4px);
        }

        &.field-empty {
          border-left-color: #f56c6c;
          background-color: #fef0f0;

          &:hover {
            background-color: #fde2e2;
          }
        }

        .field-name {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          color: #303133;

          .el-icon {
            font-size: 16px;
          }
        }

        .field-status {
          flex-shrink: 0;
        }
      }
    }
  }
}
</style>

